# vim: ai ts=2 sts=2 et sw=2

import pygame
import random

import utils
import world

class Unit():
  """
  This class covers anything in the world that is alive.
  """
  def __init__(self, imageName):
    self.image = utils.load_image(imageName)
    
    # position in the world
    self.x = 0
    self.y = 0

    # energy variables
    self.maxEnergy = 100
    self.regenEnergy = 10
    self.energy = 0

    # hunger
    self.hunger = 0

    # current job
    self.job = None
    
  def update(self, world):
    self.regenerate()

    if self.job is not None:
      self.doJob(world)
    else:
      self.wander(world)

  def regenerate(self):
    if self.energy < self.maxEnergy:
      self.energy += self.regenEnergy

    self.hunger += 1

  def doJob(self, world):
    if len(self.job.path) == 0:
      self.job.path = world.map.findPath((self.x, self.y), (self.job.destination))
      if self.job.path is None:
        self.job = None
        return
    else:
      x, y = self.job.path[-1]
      if self.move(x, y, world):
        self.job.path.pop()

    if len(self.job.path) == 0:
      self.job = None

  def wander(self, world):
    deltaX = random.randint(-1, 1)
    deltaY = random.randint(-1, 1)
    self.move(self.x + deltaX, self.y + deltaY, world)

  def move(self, x, y, world):
    if x < 0:
      x = 0
    if x > world.map.width - 1:
      x = world.map.width - 1
  
    if y < 0:
      y = 0
    if y > world.map.height - 1:
      y = world.map.height - 1 
  
    if world.map.tiles[world.map.data[x, y]].cost <= self.energy:
      self.energy -= world.map.tiles[world.map.data[x, y]].cost
      self.x = x
      self.y = y
      return True
    else:
      return False
    
